<template>
  <div id="app" class="evaluation">
    <a-card>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart2" v-if="!searchData.studentId" :style="{width:'100%',height:'368px'}"></div>
      <!-- <div ref="lineChart3" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart3" :style="{width:'100%',height:'368px'}"></div> -->
    </a-card>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'
export default {
  name: 'evaluation',
  data() {
    return {
      url: {
        query: '/management/skStudentEvaluation/getEvaluationStatistical',
      },
      searchData: {
        semesterId: '',
        classId: '',
        studentId: '',
      },
      dataList:[],
      numList:[]
    }
  },
  props:["dataForm","semesterName","className"],
  components: {},

  filters: {},

  computed: {},

  created() {},

  activated() {},

  mounted() {
    this.load();
  },

  methods: {
    // 查询接口
    initQueryChart(data){
      // byType     按日统计-day，按月统计-month，整个时间段-all
      // statisticalScope     all-按全园，class-按班级，student-按学生
      // evaluationCategory     评价种类(0-学校,1-家长)
      // timeScope     选学期时传学期ID，选月份时传空
      // startDate     开始时间，选月份时传月份开始截至时间
      // endDate     截至时间
      // classId     班级id
      // studentId    学生ID
      return new Promise((resolve, reject) => {
        let queryParams = Object.assign({evaluationCategory:1}, data);
        getAction(this.url.query,queryParams).then((res)=>{
          if(res.success){
            resolve(res.result)
          } else {
            this.$message.warning(res.message);
          }
        }).catch((error)=>{
          console.error(error);
        })
      })
    },
    // 加载报表
    load() {
      const dataForm = this.dataForm
      // 查询列表数据
      console.log('sssssssssssss',this.dataForm);
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      if(dataForm.studentId) {
        this.initStudentChart();
      } else if(dataForm.classId) {
        this.initClassChart();
      } else{
        this.initAllChart();
      }
    },
    // 所有报表
    initAllChart() {
      this.monthChart()
      this.classChart()
    },
    // 每月
    async monthChart() {
      const params = {
        byType:"month",
        statisticalScope: 'all',
        timeScope: this.searchData.semesterId,
      }
      let data = await this.initQueryChart(params)
      //全园月平均
      let categorys = [],xData1 = [],xData2 = [];
      const monthColumns = this.dataForm.monthColumns;
      for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
        const rowString = monthColumns[rowIndex].toString();
        categorys.push(rowString);
        const monthData = data.find(item => item.evaluationDate == rowString);
        if (monthData){
          xData1.push((monthData.avgNum).toFixed(2));
          xData2.push((monthData.totalNum).toFixed(2));
        } else {
          xData1.push(0);
          xData2.push(0);
        }
      }
      this.initLineChart(this.$refs.lineChart1, '每月评价数',categorys, xData1, xData2);
    },
    // 每班
    async classChart() {
      const params = {
        byType:"all",
        statisticalScope: 'class',
        timeScope: this.searchData.semesterId,
      }
      let data = await this.initQueryChart(params)
      // 各班平均
      let categorys = [],xData1 = [],xData2 = [];
      const classList = this.dataForm.classList.filter(item => { return item.id != ''});
      classList.forEach(el => {
        categorys.push(el.className);
        const classData = data.find(item => item.classId == el.id);
        if (classData){
          xData1.push((classData.avgNum).toFixed(2));
          xData2.push((classData.totalNum).toFixed(2));
        } else {
          xData1.push(0);
          xData2.push(0);
        }
      });
      this.initLineChart(this.$refs.lineChart2, '全班月评价数', categorys, xData1, xData2);
    },
    initClassChart() {
      this.monthClassChart();
      this.classStudentChart();
    },
    async monthClassChart() {
      const params = {
        byType:"month",
        statisticalScope: 'class',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      let data = await this.initQueryChart(params)
      let categorys = [],xData1 = [],xData2 = [];
      const monthColumns = this.dataForm.monthColumns;
      for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
        const rowString = monthColumns[rowIndex].toString();
        categorys.push(rowString);
        const monthData = data.find(item => item.evaluationDate == rowString);
        if (monthData){
          xData1.push((monthData.avgNum).toFixed(2));
          xData2.push((monthData.totalNum).toFixed(2));
        } else {
          xData1.push(0);
          xData2.push(0);
        }
      }
      this.initLineChart(this.$refs.lineChart1, '每月评价数',categorys, xData1, xData2);
    },
    async classStudentChart() {
      const params = {
        byType:"all",
        statisticalScope: 'student',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      let data = await this.initQueryChart(params)
      let categorys = [],xData1 = [],xData2 = [];
      data.forEach(student => {
        categorys.push(student.studentName);
        xData1.push((student.num).toFixed(2));
        xData2.push((student.totalNum).toFixed(2));
      })
      this.initLineChart(this.$refs.lineChart2, '幼儿学期平均评价数/总评价数对比',categorys, xData1, xData2);
    },
    async initStudentChart(){
      const params = {
        byType:"month",
        statisticalScope: 'student',
        timeScope: this.searchData.semesterId,
        classId: this.searchData.classId,
        studentId: this.searchData.studentId,
      }
      let data = await this.initQueryChart(params)
      //全园月平均
      let categorys = [],xData1 = [],xData2 = [];
      const monthColumns = this.dataForm.monthColumns;
      for(let rowIndex = 0; rowIndex < monthColumns.length; rowIndex++){
        const rowString = monthColumns[rowIndex].toString();
        categorys.push(rowString);
        const monthData =data.find(item => item.evaluationDate == rowString);
        if (monthData){
          xData2.push((monthData.totalNum).toFixed(2));
        } else {
          xData2.push(0);
        }
      }
      this.initLineChart(this.$refs.lineChart1, '每月总评价数',categorys, xData1, xData2,['','总评价数']);
    },
    initLineChart(el, title, categorys, xData1, xData2,legendTitle = ['平均评价数', '总评价数']) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      // var legendTitle = legendTitle;
      // option
      let optionSports = {
        backgroundColor: '#fff',
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.semesterName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          y: 'top', //延Y轴居中 
          x: 'right', //居右显示
          right: '15%'
        },
        grid: {
          left: '10%',
          top: '15%',
          right: '10%',
          bottom: '10%'
        },
        xAxis: {
          data: categorys,
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          }
        },
        yAxis: [
          {
            // name: legendTitle[0],
            splitLine: {
              show: false
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#999'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          },
          // {
          //   name: legendTitle[1],
          //   splitLine: {
          //     show: false
          //   },
          //   axisLine: {
          //     show: true,
          //     lineStyle: {
          //       color: '#999'
          //     }
          //   },
          //   nameTextStyle: {
          //     color: '#999'
          //   },
          //   splitArea: {
          //     show: false
          //   }
          // },
        ],
        series: [
          {
            name: legendTitle[0],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#0BA6E3',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData1
          },
          {
            name: legendTitle[1],
            type: 'line',
            smooth: true,
            showAllSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            // yAxisIndex: 1,
            itemStyle: {
              normal: {
                color: '#FFC005',
                label : {
                  show: true // 显示数据
                },
              }
            },
            data: xData2
          },
        ]
      }

      myChartSports.setOption(optionSports);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if(this.dataForm.studentId) {
        if (this.numList.length == 1) {
          this.$emit("ok")
        }
      }else if(this.dataForm.classId) {
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }else{
        if (this.numList.length == 2) {
          this.$emit("ok")
        }
      }
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
